package com.wuseguang.springcloud.controller;


import com.alibaba.fastjson.JSONObject;
import com.wuseguang.springcloud.Filter.RequestParameterWrapper;
import com.wuseguang.springcloud.JdbcTemplate.BaseTemplate;
import com.wuseguang.springcloud.JdbcTemplate.WXJdbc;
import com.wuseguang.springcloud.dao.repository.TeacherRepository;
import com.wuseguang.springcloud.entity.Teacher;
import com.wuseguang.springcloud.service.TeacherService;
import com.wuseguang.springcloud.util.*;
import com.wuseguang.springcloud.util.WeChat.WXUtil;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * <p>
 * 教师表/教职工表 前端控制器
 * </p>
 *
 * @author
 * @since 2019-11-17
 */
@RestController
public class TeacherController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private TeacherService TeacherServiceImpl;

    @Autowired
    private TeacherRepository teacherRepository;

    @Autowired
    private BaseTemplate baseTemplate;


    @Autowired
    private WXJdbc wXJdbc;

    /**
     * 教师登录
     *
     * @param response
     * @param phone    手机号码
     * @param pwd      密码
     * @param type     登录类型  0 web登录，1小程序登录
     * @param code     小程序code
     * @return
     */
    @RequestMapping("/tlogin")
    public Result tlogin(HttpServletResponse response,
                         @RequestParam("phone") String phone,
                         @RequestParam("pwd") String pwd,
                         @RequestParam(value = "type", defaultValue = "0") Integer type,
                         @RequestParam(value = "code", required = false) String code) {

        //判断手机号码是否为空
        if (StringUtils.isEmpty(phone)) {
            logger.info("mobile is null");
            return new Result(CodeUtil.MOBILE_IS_NULL);
        }
        //判断密码是否为空
        if (StringUtils.isEmpty(pwd)) {
            logger.info("pwd is null");
            return new Result(CodeUtil.PWD_IS_NULL);
        }
        //根据手机号码查询老师信息
        Teacher teacher = teacherRepository.findByPhone(phone);

        //判断如果手机号码为空
        if (teacher == null) {
            logger.info("user does not exist");
            return new Result(CodeUtil.USER_DOES_NOT_EXIST);
        }

        //判断密码是否正确
        if (!MyDES.decryptBasedDes(teacher.getPassword()).equals(pwd)) {
            logger.info("password error");
            return new Result(CodeUtil.PASSWORD_ERROR);

        }
        //查询出的所有权限
        List<Map<String, Object>> list = null;
        //查询是不是校级管理员角色
        String sql = "select COUNT(1) count from teacher_role where teacher_id = ? and role_id =1";
        Integer admin = baseTemplate.queryCount(sql,teacher.getId());
        //判断如果有校级管理员的角色
        if(admin>0){
            teacher.setAdmin(0);
        }


            //判断是否是管理员
            if (teacher.getAdmin() == 0) {
                logger.info("查询学校管理员的权限");
                list = findAdminJurisdiction(teacher.getSchoolId());
            } else {
                logger.info("查询学校非管理员的权限");
                list = findNoAdminJurisdiction(teacher.getId(), teacher.getSchoolId());

            }


        //查询学期id
         sql = "select id string from school_year where school_id  =?  and state = 0";
        //学期id
        String termId = baseTemplate.queryString(sql, teacher.getSchoolId());

        sql = "select school_name string  from school where id =?";

        String schoolName = baseTemplate.queryString(sql, teacher.getSchoolId());

        teacher.setSchoolName(schoolName);

        sql = "SELECT  t.`name` teacherName, c.name dName,r.`name` roleName  FROM teacher_role tr LEFT JOIN  roles r ON(tr.role_id=r.id)  " +
                "LEFT JOIN teacher t ON(tr.teacher_id=t.id) LEFT JOIN classes c ON(tr.pid=c.id) WHERE tr.teacher_id=? AND tr.type =3  AND r.id=2 " +
                "   UNION  " +
                "select  t.`name` teacherName, c.name dName,r.`name` roleName  from teacher_role tr LEFT JOIN  roles r on(tr.role_id=r.id) " +
                "LEFT JOIN teacher t on(tr.teacher_id=t.id) LEFT JOIN classes c on(tr.pid=c.id) where tr.teacher_id=? and tr.type =3 " +
                " UNION " +
                " select  t.`name` teacherName, g.name dName,r.`name` roleName from teacher_role tr  LEFT JOIN  roles r on(tr.role_id=r.id) " +
                "LEFT JOIN teacher t on(tr.teacher_id=t.id) LEFT JOIN grade g on(tr.pid=g.id)  where tr.teacher_id=? and tr.type =2 " +
                " UNION " +
                " select t.`name` teacherName, d.`name` dName,r.`name` roleName from teacher_role tr LEFT JOIN  roles r on(tr.role_id=r.id) " +
                "LEFT JOIN department d on (tr.pid=d.id) LEFT JOIN teacher t on(tr.teacher_id=t.id)  where tr.teacher_id=? and tr.type =1 ";

        List<Map<String, Object>> roleList = baseTemplate.queryListMap(sql, teacher.getId(), teacher.getId(), teacher.getId(), teacher.getId());

        String subject = String.format("%s-%s-%s-%s-%s-%s-%s", teacher.getPhone(), teacher.getId(), teacher.getName(), teacher.getHeadPortrait(), teacher.getAdmin(), teacher.getSchoolId(), termId);

        //登录成功
        String token = Jwts.builder()
                .setSubject(subject)
                .setId(UUID.randomUUID().toString())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + JWTUtils.EXPIRATION))
                .signWith(SignatureAlgorithm.HS512, JWTUtils.SIGNINGKEY)
                .compressWith(CompressionCodecs.DEFLATE)
                .compact();


        token = JWTUtils.PREFIX_VALIDATION + token;

        response.addHeader("token", token);
        Map<String, Object> hm = new HashMap<String, Object>();
        hm.put("token", token);
        hm.put("teacher", teacher);
        hm.put("list", list);
        hm.put("roleList", roleList);

        try {
            //判断如果为小程序登录并且小程序的openId为空
            if (type == 1 && !StringUtils.isEmpty(code)) {
                //获取openId
                String openId = WXUtil.getUserOpenId("wxeef24208ca48a4c2", "eb52a0824c03d0421ef996c67af702c9", code);
                if (!"error".equals(openId)) {
                    teacher.setOpenIdOne(openId);
                    teacherRepository.save(teacher);
                }

            }

        } catch (Exception e) {
            logger.error("获取用户openId失败", e);
        }
        return new Result(hm);
    }


    /**
     * 根据学校id查询管理员的功能权限
     *
     * @param schoolId
     * @return
     */
    public List<Map<String, Object>> findAdminJurisdiction(Integer schoolId) {
        //查询功能权限
        String sql = "select id,name,pid ,if(count(1)>1,1,0) as state from ( "
                + "  select jurisdiction_id  id ,jurisdiction_name name,jurisdiction_pid pid  from school_jurisdiction where jurisdiction_pid = ?  and school_id=?  AND web=1" //web端
                + " UNION  select jurisdiction_id  id ,jurisdiction_name name,jurisdiction_pid pid  from school_jurisdiction where jurisdiction_pid = ?  and school_id=?  AND tapplet=1  " //校园版小程序
                + " UNION all select id,name,pid   from jurisdiction where  pid =? AND web=1  "//web端
                + "  ) jurisdiction group by id  ";

        logger.info("管理员查询功能权限 sql= {},参数1 = {}，参数2 = {},参数3 = {}", 0, schoolId, 0);

        List<Map<String, Object>> list = baseTemplate.queryListMap(sql, 0, schoolId, 0, schoolId, 0);

        //循环一级权限
        for (Map<String, Object> s : list) {
            List<Map<String, Object>> twoList = baseTemplate.queryListMap(sql, s.get("id"), schoolId, s.get("id"), schoolId, s.get("id"));
            //循环二级权限
            for (Map<String, Object> twos : twoList) {
                List<Map<String, Object>> ThreeList = baseTemplate.queryListMap(sql, twos.get("id"), schoolId, twos.get("id"), schoolId, twos.get("id"));
                twos.put("list", ThreeList);
            }
            s.put("list", twoList);
        }

        return list;
    }

    /**
     * 非管理员查询自己拥有的功能权限
     *
     * @param teacherId
     * @return
     */
    public List<Map<String, Object>> findNoAdminJurisdiction(Integer teacherId, Integer schoolId) {
        //查询功能权限
        String sql = "select id,name,pid ,if(count(1)>1,1,0) as state from ( "
                + " select jurisdiction_id  id ,jurisdiction_name name,jurisdiction_pid pid  from school_jurisdiction where jurisdiction_pid = ?  and school_id=?  AND web=1 UNION  "//web端
                + "  select jurisdiction_id  id ,jurisdiction_name name,jurisdiction_pid pid  from school_jurisdiction where jurisdiction_pid = ?  and school_id=?  AND tapplet=1  UNION all "//小程序
                + "  select jurisdiction_id  id ,jurisdiction_name name,jurisdiction_pid pid from grouping_jurisdiction rj where exists(select * from roles r left join teacher_role t on(r.id=t.role_id)  where t.teacher_id =? and r.grouping_id=rj.grouping_id ) and  jurisdiction_pid =? and rj.school_id = ? GROUP BY jurisdiction_id "
                + "  ) jurisdiction group by id  ";

        logger.info("非管理员查询功能权限 sql= {},参数1 = {}，参数2 = {},参数3 = {}", 0, teacherId, 0, schoolId);
        //一级权限
        List<Map<String, Object>> list = baseTemplate.queryListMap(sql, 0, schoolId, 0, schoolId, teacherId, 0, schoolId);
        //循环一级权限
        for (Map<String, Object> s : list) {
            List<Map<String, Object>> twoList = baseTemplate.queryListMap(sql, s.get("id"), schoolId, s.get("id"), schoolId, teacherId, s.get("id"), schoolId);
            //循环二级权限
            for (Map<String, Object> twos : twoList) {
                List<Map<String, Object>> ThreeList = baseTemplate.queryListMap(sql, twos.get("id"), schoolId, twos.get("id"), schoolId, teacherId, twos.get("id"), schoolId);
                twos.put("list", ThreeList);
            }
            s.put("list", twoList);
        }
        return list;
    }

    /**
     * 根据公众号code 获取用户公众号openId
     * @param request
     * @param code
     * @param type 0校园版,1家长版
     * @return
     */
    @RequestMapping("/getOfficialAccountOpenId")
    public Result getOfficialAccountOpenId(RequestParameterWrapper request,
                                           @RequestParam(value = "code") String code,
                                           @RequestParam(value = "type") Integer type){

        //判断是否为校园版
        if(type==0){
            logger.info("校园版");
            String teacherId = request.getParam("teacherId");
            teacherOpenIdTwo(teacherId,code);

        }else{
            logger.info("家长版");
            String parentId =  request.getParam("parentId");
            parentOpenIdTwo(parentId,code);
        }
        return new Result();
    }

    /**
     * 获取教师的公众号openId
     * @param teacherId 教师id
     */
    public void teacherOpenIdTwo(String teacherId,String code){
        logger.info("获取教师公众号的openId");
        //获取用户openId
        Official official = WXUtil.getOfficialAccount("wx488da3b3817ff049","6385ae888eeeb70abf0bd1ba8760f1fc",code);
        //修改教师的公众号openId
        String sql = "UPDATE `teacher` SET `open_id_two` =?  WHERE `id` = ?";
        baseTemplate.updateByParameter(sql,official.getOpenId(),teacherId);
    }

    /**
     * 获取家长的公众号openId
     * @param parentId 家长id
     */
    public void parentOpenIdTwo(String parentId,String code){
        logger.info("获取家长的公众号openId");
        try {
            Official official = WXUtil.getOfficialAccount("wx488da3b3817ff049","6385ae888eeeb70abf0bd1ba8760f1fc",code);
            String accessToken = wXJdbc.getOfficialAccountAccessToken(0);

            String userInfo = WXUtil.getUserInfo(accessToken, official.getOpenId());

            JSONObject jsonObject = (JSONObject) JSONObject.parse(userInfo);

            //修改家长的公众号openId
            String sql = "UPDATE `parent` SET `open_id_two` =?,`headimgurl`=?,`nickname`=?  WHERE `id` = ?";
            baseTemplate.updateByParameter(sql,official.getOpenId(),jsonObject.get("headimgurl"),jsonObject.get("nickname"),parentId);
            logger.info("userInfouserInfo={}",jsonObject.toString());
        } catch (Exception e) {
            logger.info("获取家长信息失败");
        }
    }
}

